//
//  String+LSF.swift
//  hoonpay
//
//  Created by 李胜锋 on 2017/8/7.
//  Copyright © 2017年 lishengfeng. All rights reserved.
//

import Foundation

extension String {
    static func lsf_parse(_ anyObj:Any?) -> String? {
        var result:String?
        if anyObj is String {
            result = anyObj as? String
        }
        
        return result
    }
    
    ///判断字符串是否有值
    static func lsf_hasValue(_ string: String?) -> Bool {
        guard let string = string else {
            return false
        }
        if string.count > 0 {
            return true
        }
        return false
    }
    
    ///HTML转化成AttributedString
    func lsf_htmlAttributedString(font: UIFont) -> NSMutableAttributedString? {
        
        guard let data = self.data(using: String.Encoding.unicode, allowLossyConversion: true) else {
            return NSMutableAttributedString.init(string: self)
        }
        
        
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
        do{
            let attri = try NSMutableAttributedString.init(data: data, options: options, documentAttributes: nil)
            return attri
        }catch let error as NSError {
            print(error.localizedDescription)
        }
        
        return nil
    }
    
    ///HTML转化成AttributedString,设置段落格式
    func lsf_htmlParagraphText(font: UIFont,
                               firstLineHeadIndent: CGFloat = 0,
                               paragraphSpacing: CGFloat = 5,
                               lineSpacing: CGFloat = 5)  -> NSMutableAttributedString? {

        let attri = self.lsf_htmlAttributedString(font: font)
        
        let style = NSMutableParagraphStyle()
        style.firstLineHeadIndent = firstLineHeadIndent
        style.alignment = .left
        //段落间距
        style.paragraphSpacing = paragraphSpacing
        style.lineSpacing = lineSpacing
        let range = NSRange.init(location: 0, length: (attri?.string.count)!)
        attri?.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: range)
        
        return attri
    }
    
    func lsf_htmlFitImageSize(width: CGFloat) -> String {
        var html = ""
        html.append("<head><style>")
        html.append("img{width:%g !important;height:auto; padding-left:0;}")
        html.append("</style></head>")
        
        html = String(format: html, width)
        html.append(self)
        return  html
    }
    
}
